<template>
  <div class="home">
    <div v-if="loading" class="loading">
      <div class="spinner"></div>
    </div>
    <div v-else-if="error" class="error">
      <i class="fas fa-exclamation-circle"></i>
      <p>{{ error }}</p>
    </div>
    <div v-else class="content">
      <div class="stats">
        <div class="stat-card">
          <h3>总漏洞数</h3>
          <p>{{ processedStats.total_vulnerabilities }}</p>
        </div>
        <div class="stat-card">
          <h3>高危漏洞</h3>
          <p>{{ processedStats.by_severity.high }}</p>
        </div>
        <div class="stat-card">
          <h3>中危漏洞</h3>
          <p>{{ processedStats.by_severity.medium }}</p>
        </div>
        <div class="stat-card">
          <h3>低危漏洞</h3>
          <p>{{ processedStats.by_severity.low }}</p>
        </div>
        <div class="stat-card">
          <h3>已修复</h3>
          <p>{{ processedStats.by_severity.fixed }}</p>
        </div>
      </div>
      <div class="vulnerabilities">
        <h2>最近漏洞</h2>
        <div class="vuln-list">
          <div v-for="vuln in processedVulnerabilities" :key="vuln.id" class="vuln-item">
            <div class="vuln-header">
              <span :class="['severity', severityClass(vuln.severity)]">{{ vuln.severity }}</span>
              <span class="date">{{ vuln.published }}</span>
            </div>
            <h3>{{ vuln.package }}</h3>
            <p>{{ vuln.description }}</p>
          </div>
        </div>
        <div class="pagination">
          <button @click="prevPage" :disabled="currentPage === 1">上一页</button>
          <span>第 {{ currentPage }} 页，共 {{ totalPages }} 页</span>
          <button @click="nextPage" :disabled="currentPage === totalPages">下一页</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, onMounted, computed } from 'vue'
import api from '../services/api'

export default {
  name: 'Home',
  setup() {
    const loading = ref(true)
    const error = ref(null)
    const stats = ref(null)
    const vulnerabilities = ref([])
    const currentPage = ref(1)
    const totalPages = ref(1)
    const pageSize = ref(10)

    const processedStats = computed(() => {
      if (!stats.value) {
        return {
          total_vulnerabilities: 0,
          by_severity: {
            high: 0,
            medium: 0,
            low: 0,
            critical: 0,
            fixed: 0
          }
        }
      }
      return stats.value
    })

    const processedVulnerabilities = computed(() => {
      if (!vulnerabilities.value) return []
      return vulnerabilities.value.map(vuln => ({
        ...vuln,
        published: new Date(vuln.published).toLocaleDateString()
      }))
    })

    const severityClass = (severity) => {
      const severityMap = {
        'high': 'high',
        'medium': 'medium',
        'low': 'low',
        'critical': 'critical'
      }
      return severityMap[severity.toLowerCase()] || 'low'
    }

    const fetchData = async () => {
      try {
        loading.value = true
        error.value = null
        
        const [statsResponse, vulnsResponse] = await Promise.all([
          api.getStats(),
          api.getRecentVulnerabilities(currentPage.value, pageSize.value)
        ])
        
        if (statsResponse && typeof statsResponse === 'object') {
          stats.value = statsResponse
        }
        
        if (vulnsResponse && Array.isArray(vulnsResponse.data)) {
          vulnerabilities.value = vulnsResponse.data
          totalPages.value = Math.ceil(vulnsResponse.total / pageSize.value)
        }
        
        console.log('Fetched data:', {
          stats: stats.value,
          vulnerabilities: vulnerabilities.value,
          pagination: {
            current: currentPage.value,
            total: totalPages.value
          }
        })
      } catch (err) {
        console.error('Error fetching data:', err)
        error.value = '获取数据失败，请稍后重试'
      } finally {
        loading.value = false
      }
    }

    const nextPage = () => {
      if (currentPage.value < totalPages.value) {
        currentPage.value++
        fetchData()
      }
    }

    const prevPage = () => {
      if (currentPage.value > 1) {
        currentPage.value--
        fetchData()
      }
    }

    onMounted(() => {
      fetchData()
    })

    return {
      loading,
      error,
      processedStats,
      processedVulnerabilities,
      currentPage,
      totalPages,
      severityClass,
      nextPage,
      prevPage
    }
  }
}
</script>

<style scoped>
.home {
  padding: 20px;
}

.loading {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 200px;
}

.spinner {
  width: 40px;
  height: 40px;
  border: 4px solid #f3f3f3;
  border-top: 4px solid #3498db;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.error {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  min-height: 200px;
  color: #e74c3c;
}

.error i {
  font-size: 48px;
  margin-bottom: 16px;
}

.content {
  max-width: 1200px;
  margin: 0 auto;
}

.stats {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 20px;
  margin-bottom: 40px;
}

.stat-card {
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  text-align: center;
}

.stat-card h3 {
  margin: 0;
  color: #666;
  font-size: 16px;
}

.stat-card p {
  margin: 10px 0 0;
  font-size: 24px;
  font-weight: bold;
  color: #2c3e50;
}

.vulnerabilities {
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.vulnerabilities h2 {
  margin: 0 0 20px;
  color: #2c3e50;
}

.vuln-list {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.vuln-item {
  padding: 15px;
  border: 1px solid #eee;
  border-radius: 4px;
}

.vuln-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.severity {
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: bold;
}

.severity.high {
  background: #ffebee;
  color: #c62828;
}

.severity.medium {
  background: #fff3e0;
  color: #ef6c00;
}

.severity.low {
  background: #e8f5e9;
  color: #2e7d32;
}

.severity.critical {
  background: #fce4ec;
  color: #c2185b;
}

.date {
  color: #666;
  font-size: 14px;
}

.vuln-item h3 {
  margin: 0 0 10px;
  color: #2c3e50;
}

.vuln-item p {
  margin: 0;
  color: #666;
  line-height: 1.5;
}

.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 20px;
  margin-top: 20px;
}

.pagination button {
  padding: 8px 16px;
  border: none;
  border-radius: 4px;
  background: #3498db;
  color: white;
  cursor: pointer;
  transition: background 0.3s;
}

.pagination button:hover:not(:disabled) {
  background: #2980b9;
}

.pagination button:disabled {
  background: #bdc3c7;
  cursor: not-allowed;
}

.pagination span {
  color: #666;
}
</style> 